package com.atguigu.gulimall.product.web;

import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;
import com.atguigu.gulimall.product.vo.Catelog2Vo;
import org.redisson.api.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
/**
 * 首页
 */
@Controller
public class indexController {
    @Autowired CategoryService categoryService;
    @Autowired RedissonClient redisson;
    @Autowired StringRedisTemplate stringRedisTemplate;

    /**
     * 模拟场景：放假，学校锁门
     * 一共5个班，所有班的人都走光才可以锁门
     */
    @GetMapping("/lockDoor")
    @ResponseBody
    public String lockDoor() throws Exception {
        RCountDownLatch door = redisson.getCountDownLatch("door");    //获取闭锁
        door.trySetCount(5);    //表示有5个班
        door.await();    //等待闭锁完成，才解锁，表示等5个班的人都走光才锁门
        return "放假了...";
    }

    @GetMapping("/gogogo/{id}")
    @ResponseBody
    public String gogogo(@PathVariable("id") Long id) throws Exception {
        RCountDownLatch door = redisson.getCountDownLatch("door");    //获取闭锁
        door.countDown();    //表示计数减一，有一班人走了，就减一，直到走完5个班
        return id + "班的人都走了...";
    }


    /**
     * 模拟场景：车库停车
     * 车辆进来，共有3个车位
     */
    @GetMapping("/park")
    @ResponseBody
    public String park() throws Exception {
        RSemaphore park = redisson.getSemaphore("park");
        //park.acquire();    //获取一个信号，占一个车位, 为阻塞式获取，表示一定要获得车位才行
        boolean b = park.tryAcquire();    //表示试着获取车位，有就停，没有就算了
        if (b) {
            //执行业务
        } else {
            return "error";
        }
        return "ok => " + b;
    }

    /**
     * 模拟场景：车库停车
     * 车辆开走
     */
    @GetMapping("/go")
    @ResponseBody
    public String go() throws Exception {
        RSemaphore park = redisson.getSemaphore("park");
        park.release();    //释放一个车位
        return "ok";
    }

    @GetMapping("/write")
    @ResponseBody
    public String writeValue() {
        //1、获取锁
        RReadWriteLock lock = redisson.getReadWriteLock("rw-lock");
        String uuid = null;
        RLock writeLock = lock.writeLock();
        try {
            //1.1 加写锁
            writeLock.lock();
            System.out.println("写锁加锁成功..." + Thread.currentThread().getId());
            uuid = UUID.randomUUID().toString();
            Thread.sleep(30000);
            stringRedisTemplate.opsForValue().set("writeValue", uuid);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //2、解锁
            writeLock.unlock();
            System.out.println("写锁释放..." + Thread.currentThread().getId());
        }
        return uuid;
    }

    @GetMapping("/read")
    @ResponseBody
    public String redValue() {
        //1、获取锁
        String uuid = null;
        RReadWriteLock lock = redisson.getReadWriteLock("rw-lock");
        //1.1 加读锁
        RLock readLock = lock.readLock();
        readLock.lock();
        System.out.println("读锁加锁成功..." + Thread.currentThread().getId());
        try {
            uuid = stringRedisTemplate.opsForValue().get("writeValue");
            Thread.sleep(30000);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //2、解锁
            readLock.unlock();
            System.out.println("读锁释放..." + Thread.currentThread().getId());
        }
        return uuid;
    }


    @ResponseBody
    @GetMapping("/hello")
    public String hello() {
        //1、获取锁，只要名字一样，就是同一把锁
        RLock lock = redisson.getLock("my-lock");
        //2、加锁
        try {
            //lock.lock();    //阻塞式等待, 默认加的锁都是30s时间。
            //1)、锁的自动续期，如果业务超长，运行期间自动给锁续上新的 30s。不用担心业务时间长，锁会自动过期被删掉
            //2)、加锁的业务只要运行完成，就不会给当前锁续期，即使不手动解锁，锁默认在30s后自动删除
            lock.lock(30, TimeUnit.SECONDS);    //设置10秒钟自动解锁，自动解锁时间一定要大于业务执行时间
            System.out.println("加锁成功，执行业务方法..." + Thread.currentThread().getId());
            Thread.sleep(30000);    //睡眠30s
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //3、解锁
            System.out.println("释放锁..." + Thread.currentThread().getId());
            lock.unlock();
        }
        return "hello";
    }

    /**
     * 渲染二级、三级分类数据
     */
    @ResponseBody
    @GetMapping("/index/catalog.json")
    public Map<String, List<Catelog2Vo>> getCatelogJson() {
        Map<String, List<Catelog2Vo>> catelogJson = categoryService.getCatelogJson();
        return catelogJson;
    }

    /**
     * 首页请求，无论是"/" 还是 "index.html" 都是到首页
     */
    @GetMapping({"/", "index.html"})
    public String getIndex(Model model) {
        //获取所有的一级分类
        List<CategoryEntity> categoryEntities = categoryService.getLevel1Catagories();
        model.addAttribute("categorys", categoryEntities);    //把数据存到请求域
        return "index";
    }
}
